package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.SdkTable;
import com.letv.whatslive.model.convert.SdkTableConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by 55 on 2016/5/23.
 */
@Repository
public class SdkTableDAO extends BaseDAO {
    private static final Logger logger = LoggerFactory.getLogger(SdkTableDAO.class);

    protected String collectionName = "sdkTable";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    //在这个Id时会用的到
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }


      /**
     * 根据appId获取Sdk
     *
     * @param id
     * @return
     */
    public SdkTable getSdkTableById(Long id) {
        BasicDBObject query = new BasicDBObject();
        SdkTable SdkTable = new SdkTable();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            SdkTable = SdkTableConvert.castDBObjectToSdkTable(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return SdkTable;
    }

    /**
     * 获取数据通过AppId
     * */
    public SdkTable getSdkTableByAppId(Long appId) {
        BasicDBObject query = new BasicDBObject();
        SdkTable SdkTable = new SdkTable();
        query.put("appId", appId);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            SdkTable = SdkTableConvert.castDBObjectToSdkTable(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return SdkTable;
    }

    /**
     * 获取数据通过sdkName
     * */
    public SdkTable getSdkTableBySdkName(String sdkName) {
        BasicDBObject query = new BasicDBObject();
        SdkTable SdkTable = new SdkTable();
        query.put("sdkName", sdkName);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            SdkTable = SdkTableConvert.castDBObjectToSdkTable(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return SdkTable;
    }


    public Long countSdkTableByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 更新sdk
     *
     * @param
     */
    public void updateSdkTable(SdkTable sdkTable) {
        DBObject update = new BasicDBObject();
        update.put("_id", sdkTable.getId());
        BasicDBObject setValue = (BasicDBObject) SdkTableConvert.castSdkTableToDBObject(sdkTable);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }

        if(sdkTable.getAppId() != null){
            update.put("appId", sdkTable.getAppId());
        }

        if(StringUtils.isEmpty(sdkTable.getSdkName())){
            update.put("sdkName", sdkTable.getSdkName());
        }

        if(StringUtils.isEmpty(sdkTable.getCreateTime())){
            update.put("createTime", sdkTable.getCreateTime());
        }

        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(update, values);
    }



    public Long saveOrUpdate(SdkTable sdkTable) {
        DBObject query = new BasicDBObject("_id", sdkTable.getId());
        DBObject dbo = this.dbCollection.findOne(query);
        if (dbo == null) {
            if(sdkTable.getId()==null)
                sdkTable.setId(getAutoIncrementId());
            sdkTable.setCreateTime(refFormatNowDate());
            dbo = SdkTableConvert.castSdkTableToDBObject(sdkTable);
            if (dbo != null) {
                this.dbCollection.save(dbo);
                return ObjUtils.toLong(dbo.get("_id"));
            }
        } else {
            DBObject update = new BasicDBObject();
            if(sdkTable.getAppId() != null){
                update.put("appId", sdkTable.getAppId());
            }

            if(!StringUtils.isEmpty(sdkTable.getSdkName())){
                update.put("sdkName", sdkTable.getSdkName());
            }


            this.dbCollection.update(query, new BasicDBObject("$set", update), false, false);
        }

        return 0L;
    }


    /**
     * 保存数据
     * */
    public Integer saveSdkTable(SdkTable sdkTable) {
        try {

            sdkTable.setId(getAutoIncrementId());
            sdkTable.setCreateTime(refFormatNowDate());

            DBObject dbo = SdkTableConvert.castSdkTableToDBObject(sdkTable);
            WriteResult wr = this.dbCollection.insert(dbo);
            Integer integer =  wr.getN();
            return integer;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     *   根据条件查询
     * */
    public List<SdkTable> getSdkTableListByParams(Map<String, Object> params, Map orders, Integer start, Integer limit) {
        List<SdkTable> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).sort(order).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                SdkTable sdkTable = SdkTableConvert.castDBObjectToSdkTable(dbObject);
                result.add(sdkTable);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return result;
    }

    /**
     *   根据条件查询
     * */
    public List<SdkTable> getAllSdkTableList() {
        List<SdkTable> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = new BasicDBObject();
            BasicDBObject order = new BasicDBObject();
            order.append("appId", 1);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                SdkTable sdkTable = SdkTableConvert.castDBObjectToSdkTable(dbObject);
                result.add(sdkTable);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return result;
    }



    /**
     * 根据查询条件Mapg构建查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {

            if (params.get("appId") != null) {
                query.put("appId", ObjectUtils.toLong(params.get("appId")));
            }

            if (params.get("sdkName") != null) {
                Pattern pattern = Pattern.compile("^.*" + ObjectUtils.toString(params.get("sdkName")) + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("sdkName", pattern);
            }

        }

        return query;
    }


    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if (null != orders && orders.size() > 0) {
            for (String key : orders.keySet()) {
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        } else {
            //默认按照id倒序排序
            order.append("_id", -1);
        }
        return order;
    }


    public String refFormatNowDate() {
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String retStrFormatNowDate = sdFormatter.format(nowTime);

        return retStrFormatNowDate;
    }
}